<template>
    <div>
        <div :id="qrid" class="qrcode" ref="qrCodeImage" v-show="imgData == ''"></div>
        <!-- <a ref="downLoadImgUrl" style="display: none"></a>
        <el-button type="text" @click="downQrcodeImg">下载二维码</el-button> -->
    </div>
</template>
<script>
import QRCode from "qrcodejs2";
export default {
    name: "QrCode",
    props: ["qrid", "qrContent", "qrWidth", "qrHeight", "qrTitle", "qrName"],
    data() {
        return {
            dialogVisible: false,
            dialogImageUrl: "",
            imgData: "",
            qrcodeImgUrl: '',
            qrcodeImgUrlData: ''
        };
    },
    watch: {
        //监听二维码内容值的变化，重新生成二维码
        qrContent: function (val) {
            this.qrcode();
        }
    },
    created() { },
    mounted() {
        setTimeout(() => {
            this.generatorQrcode();
        }, 300);
    },
    methods: {
        /**
         * 二维码生成
         * @param content 生成二维码内容
         * @param desc 二维码底部描述
         * @param qrcodeDom 挂在dom
         * @returns {*|HTMLDivElement}
         */
        generatorQrcode() {
            const qrcodeContent = document.getElementById(this.qrid)
            qrcodeContent.width = `${this.qrWidth}px`
            qrcodeContent.height = `${this.qrHeight}px`
            const qrcodeCanvas = new QRCode(qrcodeContent, {
                text: this.qrContent, // 需要转换为二维码的内容
                width: this.qrWidth,
                height: this.qrHeight,
                colorDark: '#000000',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.H
            })
            var resolutionMultiple = 1 // 分辨率倍数
            var borderSize = 3 * resolutionMultiple // 边框留白
            var canvasWidth = 1 * this.qrWidth // 图片宽度
            // 判断 参数为空的命名情况
            var textB = this.qrName ? this.qrTitle + '  ' + this.qrName : this.qrTitle// 底部文字
            var fontSize = 30  // 文字大小
            let gegitTitle = this.qrName ? 15 : 3

            var canvasHeight = canvasWidth + fontSize * 1.5 + gegitTitle
            var canvas = document.createElement('canvas')
            if (!canvas.getContext) return
            canvas.width = canvasWidth
            canvas.height = canvasHeight

            var ctx = canvas.getContext('2d')
            ctx.fillStyle = 'rgb(255,255,255)' // 调色(纯白)
            ctx.fillRect(0, 0, canvasWidth, canvasHeight) // 绘制背景

            var qrcodeSize = canvasWidth - borderSize * 2
            let gegitTitlesds = this.qrName ? 3 : 15
            ctx.drawImage(
                qrcodeContent.querySelector('canvas'),
                borderSize,
                borderSize - gegitTitlesds,
                qrcodeSize,
                qrcodeSize
            ) // 填充二维码

            ctx.fill() // 填充背景
            ctx.imageSmoothingEnabled = false;
            ctx.fillStyle = 'rgb(0,0,0)' // 调色(纯黑)
            ctx.font = 'bold' + ' ' + fontSize + 'px Arial' // 文本大小, 字体
            ctx.textAlign = 'center'
            ctx.marginTop = '10px'
            ctx.fontWeight = 'bold'
            //处理文字描述太长换行问题
            ctx = this.drawText(ctx, textB, canvasWidth / 2, qrcodeSize + borderSize, qrcodeSize)
            // ctx.fillText(
            //     text,
            //     canvasWidth / 2,
            //     qrcodeSize + borderSize,
            //     qrcodeSize
            // ) // 绘制文本
            // 清除原二维码
            // qrcodeCanvas.clear()
            let url = canvas.toDataURL('image/png');
            this.imgSrcFun(url)
            qrcodeContent.appendChild(canvas)
            Array.from(qrcodeContent.querySelectorAll('img')).forEach((item) => {
                // item.style.display = 'none'
                item.remove()
                this.qrcodeImgUrlData = item
            })
            return qrcodeContent
        },
        imgSrcFun(item) {
            this.$emit('imgSrcFun', item)
        },
        /**
         *  文字换行
         * canvas文本换行处理
         * @param ctx canvas的 2d 对象
         * @param desc 绘制的文字
         * @param x 文字X坐标
         * @param y 文字Y坐标
         * @param w 文字最大宽度
         * @param space 每行字体y坐标间隔默认17
         */
        drawText(ctx, desc, x, y, w, space = 17) {
            // ctx：canvas的 2d 对象，t：绘制的文字，x,y:文字坐标，w：文字最大宽度
            const chr = desc
            let temp = ''
            let row = []
            if (this.qrName) {
                row = [this.qrTitle, this.qrName]
            } else {
                row = [this.qrTitle]
            }

            // for (let a = 0; a < chr.length; a++) {
            //     if (ctx.measureText(temp).width < w && ctx.measureText(temp + (chr[a])).width <= w) {
            //         temp += chr[a]
            //     } else {
            //         row.push(temp)
            //         temp = chr[a]
            //     }
            // }
            // row.push(temp)
            let spacedata = this.qrName ? 27 : space
            for (let b = 0; b < row.length; b++) {
                ctx.fillText(row[b], x, y + (b + 1) * spacedata)// 每行字体y坐标间隔20
            }
            return ctx
        },
        // 下载二维码
        downQrcodeImg() {
            let qrcodeCanvas = (this.$refs.qrCodeImage.getElementsByTagName('canvas'))[0]

            this.qrcodeImgUrl = qrcodeCanvas.toDataURL('image/png'); // 作为下载图片资源
            // this.downloadResizedImage(this.qrcodeImgUrl, 300, 300, '二维码')

        },
        downloadResizedImage(imageSrc, newWidth, newHeight, fileName) {
            // 创建img元素加载图片
            let img = new Image();
            img.crossOrigin = 'anonymous'; // 处理跨域问题
            img.onload = function () {
                // 创建canvas元素
                let canvas = document.createElement('canvas');
                canvas.width = newWidth;
                canvas.height = newHeight;
                // 将图片绘制到canvas上
                let ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0, newWidth, newHeight);
                // 从canvas获取图片数据URL并触发下载
                let url = canvas.toDataURL('image/png');
                let a = document.createElement('a');
                a.href = url;
                a.download = fileName; // 设置下载的文件名
                a.click(); // 模拟点击触发下载
            };
            img.src = imageSrc; // 设置图片源地址
        },
    }
};
</script>
